-- UIAchivBonusInfo
-- DP奖励信息界面
-- create by huanghr

local ROBBER_SLIME_ID = 4;

-- UIAchivBonusInfo继承自Layer
UIAchivBonusInfo = class("UIAchivBonusInfo", function()
    return cc.Layer:create();
end);

function UIAchivBonusInfo.create(dungeonAreaId)
    return UIAchivBonusInfo.new(dungeonAreaId);
end

-- 构造函数
function UIAchivBonusInfo:ctor(dungeonAreaId)
    -- 初始化
    self:setName("UIAchivBonusInfo");
    local node = cc.CSLoader:createNode("layout/achievement/AchivBonusInfo.csb");
    self:addChild(node);
    self.node = node;

    self.dungeonAreaId = dungeonAreaId;
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("item_scrollview");
    self.CT = CT;
    self.itemScrollview = scrollview;

     local infoScrollview = CT:getChildByName("info_scrollview");
    self.infoScrollview = infoScrollview;
    self.infoScrollview:removeAllChildren();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    self.data = {};

    -- 初始化格子
    self.curIndex = 1;

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIAchivBonusInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 获得当前迷宫奖励
function UIAchivBonusInfo:initData()
    local dungeonAreaId = self.dungeonAreaId;
    local bonusList = AchievementM.queryBonus(dungeonAreaId) or {};
    local propBonusList = AchievementM.queryPropBonus(dungeonAreaId) or {};
    printTable(propBonusList, "UIAchivBonusInfo, propBonusList");

    local index = 1;
        -- 升序
    local ret = table.keys(bonusList);
    table.sort(ret);

    -- 编辑bonus的信息
    for k, v in pairs(ret) do
        local item = {};
        local bonus = bonusList[v];
        item.index = index;

        item.dp = v;
        item.isTaken = AchievementM.isBonusTaken(dungeonAreaId, index);
        item.canTake = AchievementM.canTakeBonusByIndex(dungeonAreaId, index);
        item.bonus = bonus;
        item.propBonus = propBonusList[v];

        self.data[index] = item;
        index = index + 1;
    end
end

function UIAchivBonusInfo:initItemGrids()

    -- 图标间距(横向)
    local wGap = 5;

    -- 图标间距(纵向)
    local hGap = 5;

    -- 图标宽度
    local iconWidth = 140;

    -- 图片高度
    local iconHeight = 140;

    local topHGap  = 1;
    local leftWGap = -28;

    local totalNum = #self.data;

    local scrollview = self.itemScrollview;
    scrollview:removeAllChildren();

    local initWidth = 520;

      --计算总的宽度
    local totalWidth = math.max(totalNum* (iconWidth + wGap), scrollview:getInnerContainerSize().width);

    if totalNum == 4 then
        leftWGap = -60;
        totalWidth = totalWidth + 25;
    end

    scrollview:setInnerContainerSize(cc.size(totalWidth, scrollview:getInnerContainerSize().height));

    local itemNode = cc.CSLoader:createNode("layout/achievement/DpItem.csb");
    local widget = replaceNodeWithWidget(itemNode);
    local itemName = "item";

    -- 显示
    for n = 1, totalNum do
        local child = widget:clone();
        child:setName(itemName .. n);

        local x = leftWGap + n * (iconWidth + wGap);
        local y = 115;
        child:setPositionX(x);
        child:setPositionY(y);

        self:registerDpItemTouchEvent(child, n);

        scrollview:addChild(child);
    end
end

-- 绘制当前的Item列表
function UIAchivBonusInfo:redrawItemList()
     -- 显示信息
    local totalGridCount = #self.data;

    for i = 1, totalGridCount do
        local grid = self.itemScrollview:getChildByName("item" .. i);
        if grid then
            local focusImg = findChildByName(grid, "focus");
            focusImg:setVisible(false);
            if i == self.curIndex then
                focusImg:setVisible(true)
            end

            local hint = findChildByName(grid, "hint");
            hint:setVisible(false);

            -- 初始化格子信息
            local info = self.data[i];

            -- 已领取打上标签
            if info.isTaken then
                -- 背景图标半透显示
                local bg = findChildByName(grid, "bg");
                bg:setOpacity(125);

                local icon = findChildByName(grid, "icon");
                icon:setOpacity(125);

                -- 显示已领取
                local dpLabel = findChildByName(grid, "dp_label");
                TextStyleM.setTextStyle(dpLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -3);
                dpLabel:setString(getLocStr("has_received"));

            else
                -- 显示已领取
                local bg = findChildByName(grid, "bg");
                bg:setOpacity(255);

                local icon = findChildByName(grid, "icon");
                icon:setOpacity(255);

                local dpLabel = findChildByName(grid, "dp_label");
                TextStyleM.setTextStyle(dpLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_WHITE);
                dpLabel:setString(tostring(info.dp));

                -- 可领取有呼吸效果
                if info.canTake and i ~= self.curIndex then
                    playBubbleAnima(hint, false, 0.8);
                end
            end
        end
    end
end

function UIAchivBonusInfo:registerDpItemTouchEvent(node, index)
    -- 点击处理
    local bg = node:getChildByName("bg");

    -- 显示奖励内容
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("workshop_material");
            self.curIndex = index;
            self:redrawItemList();
            self:initInfoGrids(index);
        end
    end);

end

-- 初始化奖励信息
function UIAchivBonusInfo:initInfoGrids()
    local scrollview = self.infoScrollview;
    scrollview:removeAllChildren();
    local itemNode = cc.CSLoader:createNode("layout/achievement/DungeonAchivItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    local info = self.data[self.curIndex];

    local bonusList = info.bonus;

    -- 扫荡时的属性加成
    local propBonusList = info.propBonus or {};
    printTable(info.propBonus, "扫荡时的属性加成");

    -- 如果不能领取则按钮置灰
    local btnGain = findChildByName(self.node, "BT/btn_take_bonus");
    local hintNode = findChildByName(btnGain, "hint");
    checkBlueBubbleStatus(hintNode, info.canTake);

    if info.canTake then
        btnGain:setEnabled(true);
        btnGain:setBright(true);
    else
        btnGain:setEnabled(false);
        btnGain:setBright(false);
    end

    -- 左边距
    local leftMargin = 10;

    -- 行间距
    local gap = 0;
    local widgetHeight = 61;

    -- 获取记录总数
    local totalNum = #bonusList + #propBonusList;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = math.max(totalNum*(widgetHeight + gap), scrollview:getInnerContainerSize().height);
    startHeight = totalHeight;

    if totalHeight < scrollview:getInnerContainerSize().height then
        -- 不足一页时，修正一下起始位置
        startHeight = scrollview:getInnerContainerSize().height;
    end
    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    -- 不同语言版本缩进不同
    local kerning = -1;
    if getLang() == "zh" or getLang == "tw" then
        kerning = -3;
    end

    local i = 1;

    -- 先显示扫荡时的属性加成
    for _, bonus in pairs(propBonusList) do
        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight - i * (widgetHeight + gap) - 15;
        child:setPositionX(x);
        child:setPositionY(y);

        local line2 = findChildByName(child, "line2");
        line2:setVisible(false);
        if i == 1 then
            line2:setVisible(true);
        end
        i = i + 1;

        -- 加载当前奖励标示
        local icon = findChildByName(child, "icon");
        if tonumber(bonus[1]) > 0 then
            -- 物品奖励
            icon:loadTexture(getItemSmallIconPath(ItemM.query(tonumber(bonus[1]), "icon")));
        elseif bonus[1] == "finish_task" then
            icon:loadTexture(getItemIconPath("7127"));
            icon:setScale(0.65);
        else
            -- 属性加成奖励
            icon:loadTexture(getSmallHeroIconPath(PetM.getDefaultIcon(ROBBER_SLIME_ID)));
        end

        local desc = AchievementM.getPropBonusDesc(bonus, self.dungeonAreaId);
        local countPerLine = 17;
        if not isFullWidthLang() then
            countPerLine = 22;
        end

        -- 当前已领取字体灰色（已领取）
        local bonusLabel = findChildByName(child, "desc");
        if info.isTaken then
            TextStyleM.setTextStyle(bonusLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY, nil, kerning, nil, nil, countPerLine);
            bonusLabel:setString(desc .. getLocStr("signed"));
        elseif info.canTake then
            -- 可领取（绿色）
            TextStyleM.setTextStyle(bonusLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN, nil, kerning, nil, nil, countPerLine);
            bonusLabel:setString(desc.. getLocStr("can_sign"));
        else
            -- 不能领取黑色（需要DP值）
            TextStyleM.setTextStyle(bonusLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, kerning, nil, nil, countPerLine);
            bonusLabel:setString(desc.. string.format(getLocStr("need_dp"), info.dp));
        end
        self.infoScrollview:addChild(child);
    end

    -- 奖励类型
    for _, bonus in pairs(bonusList) do
        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight - i * (widgetHeight + gap) - 15;
        child:setPositionX(x);
        child:setPositionY(y);

        local line2 = findChildByName(child, "line2");
        line2:setVisible(false);
        if i == 1 then
            line2:setVisible(true);
        end

        i = i + 1;

        -- 加载当前奖励标示
        local icon = findChildByName(child, "icon");
        local desc = "";
        if bonus[1] == 1 then
            -- 物品奖励
            icon:loadTexture(getItemSmallIconPath(ItemM.query(bonus[2], "icon")));
            desc = desc.. ItemM.query(bonus[2], "name");
            desc = desc .. "×".. bonus[3];
        elseif bonus[1] == 2 then
            -- 属性奖励
            icon:loadTexture(getSmallAttribIconPath(FieldsM.query(bonus[2], "icon")));
            desc = desc.. FieldsM.query(bonus[2], "name");
            desc = desc .. "×".. bonus[3];
        end

        local countPerLine = 17;
        if not isFullWidthLang() then
            countPerLine = 22;
        end

        -- 当前已领取字体黑色（已领取）
        local bonusLabel = findChildByName(child, "desc");
        if info.isTaken then
            TextStyleM.setTextStyle(bonusLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY, false, kerning, nil, nil, countPerLine);
            bonusLabel:setString(desc .. getLocStr("signed"));
        elseif info.canTake then
            -- 可领取（绿色）
            TextStyleM.setTextStyle(bonusLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN, false, kerning, nil, nil, countPerLine);
            bonusLabel:setString(desc.. getLocStr("can_sign"));
        else
            -- 不能领取灰色（需要DP值）
            TextStyleM.setTextStyle(bonusLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, kerning, nil, nil, countPerLine);
            bonusLabel:setString(desc.. string.format(getLocStr("need_dp"), info.dp));
        end
        self.infoScrollview:addChild(child);
    end
end

-- 重绘当前界面
function UIAchivBonusInfo:redraw()
    -- 显示标题
    -- 关卡名称
    local dungeonName = DungeonAreaM.query(self.dungeonAreaId, "name");
    local titleLabel = findChildByName(self.CT, "template/title");
    titleLabel:setString(dungeonName);
    TextStyleM.setTitleStyle(titleLabel);

    -- 现有的DP
    local curDp = AchievementM.calcCurDp(self.dungeonAreaId);
    local dps = AchievementM.queryBonusDps(self.dungeonAreaId);
    local maxDp = dps[#dps];
    local str2 = string.format("%d/%d dp", curDp, maxDp);
    local subHeadLabel = findChildByName(self.CT, "template/subhead");
    subHeadLabel:setString(str2);
    TextStyleM.setSubheadStyle(subHeadLabel);

    self:initData();
    self:initItemGrids();
    self:redrawItemList();
    self:initInfoGrids();
end

-- 注册商品点击事件
function UIAchivBonusInfo:registerItemTouchEvent(node, index)
    -- 点击处理
    local bonusList = GroupPurchaseM.calcBonus(self.goodsId, index);
    local bg = node:getChildByName("bg");

    -- 物品奖励的时候才需要显示奖励内容
    if bonusList[1] == 1 then
        bg:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("workshop_material");
                -- 显示道具详细信息
                local uiItemDesc = UIGroupBonusDesc.create(bonusList, self.goodsId, index);
                UIMgr:getCurrentScene():addForm(uiItemDesc);
            end
        end);
    end
end

-- 注册事件处理回调函数
function UIAchivBonusInfo:registerEventCallback()
    -- 注册领取成就奖励的事件回调
    EventMgr.register("UIAchivBonusInfo", event.TAKE_ACHIV_BONUS, function(args)
        local bonusList = args.bonus;

        if type(bonusList) == "table" and #bonusList > 0 then
            -- 显示奖励领取窗口
            showBonusNotifyForm(getLocStr("dungeon_achiv_bonus_tip"), bonusList);
        end

        self:initData();
        -- self:initItemGrids();
        self:redrawItemList();
        self:initInfoGrids();
    end);

    -- 在迷宫信息界面打开该页面
    if DungeonM.isInDungeon() then
        EventMgr.register("UIAchivBonusInfo", event.FOCUS_CHANGED, function(para)
            if para["get"] == "UIAchivBonusInfo" then
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
                UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 2);
            end
        end);
    end

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIAchivBonusInfo 界面析构清理");
            EventMgr.removeAll("UIAchivBonusInfo");

            if DungeonM.isInDungeon() then
                -- 还原TopMenu的ZOrder
                local topMenu = UIMgr:getCurrentScene().topMenu;
                if topMenu then
                    topMenu:setVisible(self.oldVisible);
                    topMenu:setLocalZOrder(self.oldZOrder);
                end
            end

        elseif ev == "enter" then
            if DungeonM.isInDungeon() then
                -- 临时调高TOP_MENU的ZOrder
                local topMenu = UIMgr:getCurrentScene().topMenu;
                self.oldVisible = topMenu:isVisible();
                UIMgr.getCurrentScene().topMenu:setVisible(true);
                self.oldZOrder = topMenu:getLocalZOrder();
            end
        end
    end);
end

-- 注册点击事件
function UIAchivBonusInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIAchivBonusInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册领奖按钮
    local gainBtn = findChildByName(self.node, "BT/btn_take_bonus");
    local function onGainClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 判断能否领取奖励
            local ret = AchievementM.canTakeBonus(self.dungeonAreaId);
            if ret ~= true then
                return false;
            end

            -- 请求领取奖励
            Operation.cmd_take_achiv_bonus(self.dungeonAreaId, self.curIndex);
        end
    end
    gainBtn:addTouchEventListener(onGainClick);
    TextStyleM.setTextStyle(gainBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    gainBtn:setTitleText(getLocStr("btn_text_award"));
end

-- 隐藏template上部的bg
function UIAchivBonusInfo:hideTemplateBg()
    local template = findChildByName(self.node, "CT/template");
    local bgType   = findChildByName(template, "bg_type");
    local bgType2  = findChildByName(template, "bg_type2");
    bgType:setVisible(false);
    bgType2:setVisible(false);
end
